import { useCallback, useMemo, useState } from 'react'

export const BASE_CAPITAL = 1000000

const calcSummary = (history, trades) => {
  if (!history || history.length < 2) {
    const wins = trades.filter(t => t > 0).length
    const losses = trades.filter(t => t <= 0).length
    return {
      winRate: 0,
      maxDrawdown: 0,
      totalReturn: 0,
      maxReturn: 0,
      annualReturn: 0,
      tradeCount: trades.length,
      wins,
      losses
    }
  }
  const equities = history.map(item => item.equity)
  const timestamps = history.map(item => item.timestamp ?? Date.now())
  const startEquity = equities[0]
  const endEquity = equities[equities.length - 1]
  const totalReturn = ((endEquity - startEquity) / startEquity) * 100
  let peak = equities[0]
  let maxDrawdown = 0
  equities.forEach(value => {
    if (value > peak) {
      peak = value
    }
    const drawdown = peak === 0 ? 0 : (peak - value) / peak
    if (drawdown > maxDrawdown) {
      maxDrawdown = drawdown
    }
  })
  const maxEquity = Math.max(...equities)
  const maxReturn = ((maxEquity - startEquity) / startEquity) * 100
  const wins = trades.filter(p => p > 0).length
  const losses = trades.filter(p => p <= 0).length
  const winRate = trades.length ? (wins / trades.length) * 100 : 0
  const startTs = timestamps[0]
  const endTs = timestamps[timestamps.length - 1]
  const totalDays = Math.max(1, (endTs - startTs) / (1000 * 3600 * 24))
  const annualReturn = totalDays > 0 ? ((endEquity / startEquity) ** (365 / totalDays) - 1) * 100 : totalReturn
  return {
    winRate,
    maxDrawdown: maxDrawdown * 100,
    totalReturn,
    maxReturn,
    annualReturn,
    tradeCount: trades.length,
    wins,
    losses
  }
}

export const useStrategyBacktest = () => {
  const [equityHistory, setEquityHistory] = useState([])
  const [trades, setTrades] = useState([])
  const [summaryVisible, setSummaryVisible] = useState(false)
  const [summary, setSummary] = useState(null)
  const [finalized, setFinalized] = useState(false)

  const recordEquity = useCallback((timestamp, equity) => {
    setEquityHistory(prev => [...prev, { timestamp: timestamp ?? Date.now(), equity }])
  }, [])

  const registerTrade = useCallback(profitRatio => {
    setTrades(prev => [...prev, profitRatio])
  }, [])

  const reset = useCallback(() => {
    setEquityHistory([])
    setTrades([])
    setSummary(null)
    setSummaryVisible(false)
    setFinalized(false)
  }, [])

  const finalize = useCallback(() => {
    if (finalized) return
    const stats = calcSummary(equityHistory, trades)
    setSummary(stats)
    setSummaryVisible(true)
    setFinalized(true)
  }, [equityHistory, trades, finalized])

  const SummaryModal = useMemo(() => {
    if (!summaryVisible || !summary) return null
    return (
      <div style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: 'rgba(0,0,0,0.45)',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        zIndex: 10000
      }}>
        <div style={{
          width: 320,
          borderRadius: 16,
          border: '1px solid rgba(255,255,255,0.12)',
          background: 'rgba(20,24,34,0.95)',
          padding: 24,
          color: '#FFFFFF'
        }}>
          <div style={{fontSize: 16, marginBottom: 12}}>回测总结</div>
          <div style={{display: 'flex', flexDirection: 'column', gap: 8, fontSize: 13}}>
            <div>胜率：{summary.winRate.toFixed(2)}%</div>
            <div>最大回撤：{summary.maxDrawdown.toFixed(2)}%</div>
            <div>总收益率：{summary.totalReturn.toFixed(2)}%</div>
            <div>最大收益率：{summary.maxReturn.toFixed(2)}%</div>
            <div>年化收益率：{summary.annualReturn.toFixed(2)}%</div>
            <div>交易次数：{summary.tradeCount}（盈利 {summary.wins}，亏损 {summary.losses}）</div>
          </div>
          <div style={{display: 'flex', justifyContent: 'flex-end', gap: 12, marginTop: 20}}>
            <button onClick={() => setSummaryVisible(false)}>关闭</button>
            <button onClick={() => { setSummaryVisible(false); window.location.reload() }}>返回首页</button>
          </div>
        </div>
      </div>
    )
  }, [summaryVisible, summary])

  return {
    equityHistory,
    recordEquity,
    registerTrade,
    reset,
    finalize,
    SummaryModal
  }
}
